import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/home',
      name: 'Home',
      redirect: '/welcome',
      component: () => import('../components/home/home.vue'),
      children: [
        {
          path: '/welcome',
          name: 'Welcome',
          component: () => import('../components/welcome/welcome.vue')
        },
        {
          path: '/users',
          name: 'Users',
          component: () => import('../components/users/users.vue')
        },
        {
          path: '/roles',
          name: 'Roles',
          component: () => import('../components/authorize/roles.vue')
        },
        {
          path: '/rights',
          name: 'Rights',
          component: () => import('../components/authorize/author.vue')
        },
        {
          path: '/goods',
          name: 'Goods',
          component: () => import('../components/goods/goodsList.vue')
        },
        {
          path: '/params',
          name: 'Params',
          component: () => import('../components/goods/goodsAttribute.vue')
        },
        {
          path: '/categories',
          name: 'Categories',
          component: () => import('../components/goods/goodsCategory.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../components/login/login.vue')
    }
  ]
})

/**
 * to 要访问的路径
 * from 代表从哪个路径跳转而来
 * next() 是一个函数，表示放行
 */
router.beforeEach((to, from, next) => {
  if(to.path == '/login' || to.path == '/register'){
    next();
  }else{
    let token = window.sessionStorage.getItem("token")
    if(token){
      next();
    }else {
      next('/login');
    }
  }
})

export default router
